<?php

namespace app\admin\model\workorder;

use think\File;
use think\Model;
use addons\workorder\library\General;

/**
 * 工单沟通记录模型
 */
class Records extends Model
{
    protected $name = "workorder_records";
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = null;

    // 追加属性
    protected $append = [
        'sender',
        'createtime_text',
    ];

    protected static function init()
    {

    }

    public function getSenderAttr($value, $data)
    {
        if (isset($data['user_id']) && $data['user_id']) {
            return 'user';
        } elseif (isset($data['engineer_id']) && $data['engineer_id']) {
            return 'engineer';
        } else {
            return 'none';
        }
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        return human_date($data['createtime']);
    }

    public function engineer()
    {
        return $this->hasOne('\addons\workorder\model\Engineer', 'id', 'engineer_id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function getMessageAttr($value, $data)
    {
        if ($data['message_type'] == 0 || $data['message_type'] == 3) {
            return "<div class='rich_text'>$value</div>";
        } elseif ($data['message_type'] == 1) {
            $value = cdnurl($value, true);
            return "<img src='$value' class='img_message' alt='' />";
        } elseif ($data['message_type'] == 2) {

            // 文件地址可能是完整的url，可能是cdn的url
            // 此处只能计算本地文件的大小
            $domain = cdnurl('', true);
            if (strpos($value, $domain) !== false) {
                $value = str_replace($domain, '', $value);
            }

            $filePath = str_replace('/', DS, ROOT_PATH . 'public' . $value);
            if (!file_exists($filePath)) {
                $fileExt  = General::getFileExtension($value);
                $fileSize = false;
            } else {
                $fileObj  = new File($filePath);
                $fileExt  = $fileObj->getExtension();
                $fileSize = $fileObj->getSize();
                unset($fileObj);
            }

            $fileSize   = $fileSize ? General::formatFileSize($fileSize) : '未知大小';
            $value      = cdnurl($value, true);
            $imgIconUrl = url('ajax/icon', ['suffix' => $fileExt]);
            $textHtml   = <<<HTML
<a target='_blank' href='$value'>
    <div class='file_message'>
        <img src='$imgIconUrl' alt=''>
        <div>
            <p class='file_name'>{$fileExt}文件</p>
            <p class='file_size'>$fileSize</p>
        </div>
        <div class='down_file'>
            <i class='fa fa-download'></i>
        </div>
    </div>
</a>
HTML;
            return $textHtml;

        } elseif ($data['message_type'] == 4) {
            return '<p class="text-red">以下为机密信息</p><span class="text-red">' . $value . '</span>';
        }
    }
}